package com.lv.suyiyong.hfrwork.ui

import android.content.Intent
import android.text.TextUtils
import androidx.lifecycle.lifecycleScope
import com.alibaba.android.arouter.facade.Postcard
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.facade.callback.NavigationCallback
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.GsonUtils
import com.blankj.utilcode.util.LogUtils
import com.google.gson.reflect.TypeToken
import com.lv.common.base.BaseActivity
import com.lv.common.bean.MIPushBean
import com.lv.common.im.push.HandleOfflinePushCallBack
import com.lv.common.im.push.OfflineMessageBean
import com.lv.common.im.push.OfflineMessageDispatcher
import com.lv.common.im.push.OfflinePushConfigs
import com.lv.common.im.utils.TUIUtils
import com.lv.common.network.model.DataResult
import com.lv.common.utils.ARoutUtils
import com.lv.common.utils.LogUtil
import com.lv.common.utils.MyUtils
import com.lv.common.utils.YgxUtilsKt
import com.lv.common.utils.showToast
import com.lv.service.bean.TokenBean
import com.lv.service.model.ServiceViewModel
import com.lv.service.network.BaseYgxRsp
import com.lv.service.network.onBizError
import com.lv.service.network.onBizOK
import com.lv.service.network.onSuccess
import com.lv.service.repo.UserDbHelper
import com.lv.service.repo.UserInfo
import com.lv.service.utils.YgxAroutPageKt
import com.lv.suyiyong.hfrwork.R
import com.lv.suyiyong.hfrwork.YgxApplication
import com.lv.suyiyong.hfrwork.databinding.ActivityImparseBinding
import com.tencent.imsdk.v2.V2TIMManager
import com.tencent.qcloud.tuicore.TUIConstants
import com.tencent.qcloud.tuicore.TUILogin
import com.tencent.qcloud.tuicore.interfaces.TUICallback
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.async
import org.koin.androidx.viewmodel.ext.android.viewModel

@Route(path = ARoutUtils.ImTransferActivity)
class ImTransferActivity : BaseActivity<ActivityImparseBinding>() {
    @Autowired(name = TUIConstants.TUIOfflinePush.NOTIFICATION_EXT_KEY)
    @JvmField
    var ext: String = ""
    private var mUserInfo: UserInfo? = null
    private val viewModel: ServiceViewModel by viewModel()
    private val myScope: CoroutineScope = CoroutineScope(SupervisorJob())
    override fun getLayoutRes() = R.layout.activity_imparse
    override fun initView() {
        super.initView()
        initStatusBar(this, true, true)
        ARouter.getInstance().inject(this)

    }


    override fun initConfig() {
        super.initConfig()
        onIntent()
    }

    private fun login(userInfo: UserInfo) {
        TUILogin.login(
            this,
            YgxApplication.getInstance().getSdkAppId(),
            userInfo.txaccid,
            userInfo.txaccidpassword,
            object :
                TUICallback() {
                override fun onSuccess() {
                    setUI()
                    YgxApplication.getInstance().registerPushManually()
                    YgxUtilsKt.sendMessgeToSelf(userInfo.txaccid, userInfo.phone)
                    handleOfflinePush()
                }

                override fun onError(errorCode: Int, errorMessage: String?) {
                    showToast("登录失败 $errorCode,errorInfo = $errorMessage")
//                    startLogin()
                    ARouter.getInstance().build(ARoutUtils.LoginActivityURL).navigation()
                    YgxUtilsKt.setAppToken("", "", "")
                    UserDbHelper.deleteUserInfo(this@ImTransferActivity)
                    LogUtils.e("imLogin errorCode = $errorCode, errorInfo = $errorMessage")
                }
            })
    }

    private fun logOut() {
        TUILogin.login(
            this,
            YgxApplication.getInstance().getSdkAppId(),
            mUserInfo?.txaccid,
            mUserInfo?.txaccidpassword,
            object :
                TUICallback() {
                override fun onSuccess() {
                    TUILogin.logout(object : TUICallback() {
                        override fun onSuccess() {
                            TUILogin.logout(object : TUICallback() {
                                override fun onSuccess() {
                                    V2TIMManager.getConversationManager()
                                        .removeConversationListener(null)
                                    //清除Token
                                    YgxUtilsKt.setAppToken("", "", "")
                                    UserDbHelper.deleteUserInfo(this@ImTransferActivity)
                                }

                                override fun onError(errorCode: Int, errorMessage: String?) {
                                }
                            })
                        }

                        override fun onError(errorCode: Int, errorMessage: String?) {
                        }
                    })
                }

                override fun onError(errorCode: Int, errorMessage: String?) {
                }
            })
        showLogin()
        finish()
    }

    private fun showLogin() {
        val isExist = MyUtils.isExistActivity(this, LoginActivity::class.java)
        if (!isExist) {
            ARouter.getInstance().build(ARoutUtils.LoginActivityURL).navigation()
        }
    }

    override fun initData() {
        super.initData()

    }

    override fun onNewIntent(intent: Intent?) {
        super.onNewIntent(intent)
        /**
         * 如果Activity在，不会走到onCreate，而是onNewIntent，这时候需要setIntent
         * 场景：点击通知栏跳转到此，会收到Intent
         */
        setIntent(intent)
        onIntent()
    }


    // 处理收到的Intent
    private fun onIntent() {
        UserDbHelper.getLiveUserInfo(this).observeKt {
            if (it == null) {
                logOut()
            } else {
                mUserInfo = it
                checkToken()
            }

        }
    }

    private fun checkToken() {
        lifecycleScope.launchWhenCreated {
            val result: DataResult<BaseYgxRsp> =
                myScope.async { viewModel.refreshtoken() }.await()
            parseTokenResult(result)
        }

    }

    private fun parseTokenResult(data: DataResult<BaseYgxRsp>) {
        data.onSuccess {
            onBizOK<TokenBean> { code, data, message, result ->
                if (data != null && !TextUtils.isEmpty(data.token)) {
                    YgxUtilsKt.setAppToken(data.token, data.refreshtoken)
                    login(mUserInfo!!)
                } else {
                    logOut()
                }
            }
            onBizError<Any> { code, message, data ->
                showToast(message)
                logOut()
            }
        }
    }


    private fun setUI() {
        // 已经登录过了，处理过来的请求
        if (!TextUtils.isEmpty(ext)) {
            parseImMessage(ext)
            return
        }

    }

    private fun showHome() {
        val existActivity: Boolean = MyUtils.isExistActivity(
            this@ImTransferActivity,
            HomeActivity::class.java
        )
        if (!existActivity) {
            UserDbHelper.getLiveUserInfo(this).observeKt {
                it?.let {
                    mUserInfo = it
                }
                onIntent()
            }
            ARouter.getInstance().build(ARoutUtils.HomeActivityURL).withInt("tabId", 2).navigation()
        } else {
            setUI()
        }
    }

    //{"tt":"","t":"4","ti":"13367276910","entity":{"t":"4","ti":"13367276910","tt":""}}
    private fun parseImMessage(customContent: String?) {
//        val decode = URLDecoder.decode(customContent)
        //        String content = message.getContent();
        val jsonType = object : TypeToken<MIPushBean?>() {}.type
        val jt: MIPushBean = GsonUtils.fromJson(customContent, jsonType)
        val t = jt.t
        val ti = jt.ti
        val tt = jt.tt
        val businessID = jt.entity.businessID
        if (!businessID.isNullOrEmpty() && businessID == "2000") {
            ARouter.getInstance().build(ARoutUtils.HomeActivityURL)
                .withInt("tabId", 2)
                .navigation(
                    this,
                    object : NavigationCallback {
                        override fun onFound(postcard: Postcard?) {
                        }

                        override fun onLost(postcard: Postcard?) {
                        }

                        override fun onArrival(postcard: Postcard?) {
                            YgxAroutPageKt.aroutPager_home(this@ImTransferActivity, t, ti, tt)
                        }

                        override fun onInterrupt(postcard: Postcard?) {
                        }

                    })

        } else {
            val bean = OfflineMessageDispatcher.getOfflineMessageBeanFromContainer(ext)
            if (bean != null) {
//                refreshHomeRingMessage(bean)
                if (bean.action == OfflineMessageBean.REDIRECT_ACTION_CHAT) {
                    if (TextUtils.isEmpty(bean.sender)) {
                        return
                    }
                    TUIUtils.startChat(bean.sender, bean.nickname, bean.chatType)
                }
            }
        }

        finish()
    }

//    //发消息刷新HomeFragment铃铛通知
//    private fun refreshHomeRingMessage(v2TIMConversation: MIPushBean) {
//        LiveEventBus
//            .get(HomeRefreshEvent::class.java)
//            .post(HomeRefreshEvent(pushMessage = v2TIMConversation))
//    }
//
//    //发消息刷新HomeFragment铃铛通知
//    private fun refreshHomeRingMessage(v2TIMConversation: OfflineMessageBean) {
//        LiveEventBus
//            .get(HomeRefreshEvent::class.java)
//            .post(HomeRefreshEvent(offlineMessage = v2TIMConversation))
//    }

    private fun handleOfflinePush() {
        val intent = intent
        if (intent == null) {
            LogUtil.e("HomeActivity", "handleOfflinePush intent is null")
            return
        }
        if (OfflinePushConfigs.getOfflinePushConfigs().clickNotificationCallbackMode === OfflinePushConfigs.CLICK_NOTIFICATION_CALLBACK_INTENT) {
            TUIUtils.handleOfflinePush(
                intent,
                HandleOfflinePushCallBack { hasLogged ->
                    if (hasLogged) {
                        setIntent(null)
                    }
                })
        }
    }

    override fun finish() {
        super.finish()
        overridePendingTransition(0, 0)
    }
}